<template>
  <div class="home">
    <!-- 欢迎区域 -->
    <div class="welcome-section">
      <el-row :gutter="24" align="middle">
        <el-col :xs="24" :md="12">
          <div class="welcome-content">
            <h1 class="welcome-title">
              <span class="title-gradient">智能教案管理</span>
              <br />
              <span class="title-sub">让教学更简单高效</span>
            </h1>
            <p class="welcome-description">
              一站式教案管理平台，支持多学科、多年级教案创建与管理，
              帮助教师高效备课，提升教学质量。
            </p>
            <div class="welcome-actions" v-if="!authStore.isAuthenticated">
              <el-button type="primary" size="large" round @click="$router.push('/register')">
                开始使用 →
              </el-button>
              <el-button size="large" round plain @click="$router.push('/login')">
                登录账户
              </el-button>
            </div>
            <div class="welcome-stats" v-else>
              <div class="stat-item">
                <div class="stat-value">{{ stats.myLessonPlans }}</div>
                <div class="stat-label">我的教案</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ stats.totalSubjects }}</div>
                <div class="stat-label">学科分类</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ stats.totalGrades }}</div>
                <div class="stat-label">年级分类</div>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :md="12">
          <div class="welcome-illustration">
            <div class="illustration-bg">
              <div class="floating-card card-1">
                <el-icon :size="24"><Document /></el-icon>
              </div>
              <div class="floating-card card-2">
                <el-icon :size="24"><Reading /></el-icon>
              </div>
              <div class="floating-card card-3">
                <el-icon :size="24"><School /></el-icon>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 功能特性 -->
    <div class="features-section">
      <div class="section-header">
        <h2 class="section-title">核心功能</h2>
        <p class="section-description">专为教师设计的全方位教案管理解决方案</p>
      </div>
      
      <el-row :gutter="24" class="features-grid">
        <el-col :xs="24" :sm="12" :lg="6">
          <div class="feature-card" @click="handleCreateLesson">
            <div class="feature-icon">
              <el-icon :size="40"><DocumentAdd /></el-icon>
            </div>
            <h3>智能创建</h3>
            <p>快速创建标准化教案，支持多种模板</p>
            <div class="feature-tag">
              <el-tag size="small" type="success">新功能</el-tag>
            </div>
          </div>
        </el-col>
        
        <el-col :xs="24" :sm="12" :lg="6">
          <div class="feature-card" @click="handleViewLessons">
            <div class="feature-icon">
              <el-icon :size="40"><Folder /></el-icon>
            </div>
            <h3>分类管理</h3>
            <p>按学科、年级、课程类型等多维度管理</p>
          </div>
        </el-col>
        
        <el-col :xs="24" :sm="12" :lg="6">
          <div class="feature-card">
            <div class="feature-icon">
              <el-icon :size="40"><Search /></el-icon>
            </div>
            <h3>快速搜索</h3>
            <p>全文搜索，快速定位所需教案</p>
          </div>
        </el-col>
        
        <el-col :xs="24" :sm="12" :lg="6">
          <div class="feature-card">
            <div class="feature-icon">
              <el-icon :size="40"><Share /></el-icon>
            </div>
            <h3>团队协作</h3>
            <p>支持教案分享，促进教学交流</p>
            <div class="feature-tag">
              <el-tag size="small">敬请期待</el-tag>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 统计数据 -->
    <div v-if="authStore.isAuthenticated" class="stats-overview">
      <div class="section-header">
        <h2 class="section-title">数据概览</h2>
        <p class="section-description">实时跟踪平台使用情况</p>
      </div>
      
      <el-row :gutter="24">
        <el-col :xs="12" :sm="6">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon :size="28"><Document /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">
                <el-statistic :value="stats.totalLessonPlans" />
              </div>
              <div class="stat-label">全平台教案</div>
            </div>
            <div class="stat-trend up">
              <el-icon><Top /></el-icon>
              <span>12%</span>
            </div>
          </div>
        </el-col>
        
        <el-col :xs="12" :sm="6">
          <div class="stat-card">
            <div class="stat-icon" style="background: #ecf5ff; color: #409eff;">
              <el-icon :size="28"><User /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">
                <el-statistic :value="stats.myLessonPlans" />
              </div>
              <div class="stat-label">我的教案</div>
            </div>
            <div class="stat-trend up">
              <el-icon><Top /></el-icon>
              <span>8%</span>
            </div>
          </div>
        </el-col>
        
        <el-col :xs="12" :sm="6">
          <div class="stat-card">
            <div class="stat-icon" style="background: #f0f9ff; color: #67c23a;">
              <el-icon :size="28"><Reading /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">
                <el-statistic :value="stats.totalSubjects" />
              </div>
              <div class="stat-label">学科分类</div>
            </div>
          </div>
        </el-col>
        
        <el-col :xs="12" :sm="6">
          <div class="stat-card">
            <div class="stat-icon" style="background: #fef0f0; color: #f56c6c;">
              <el-icon :size="28"><School /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">
                <el-statistic :value="stats.totalGrades" />
              </div>
              <div class="stat-label">年级分类</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 最近教案 -->
    <div v-if="authStore.isAuthenticated && recentLessonPlans.length > 0" class="recent-section">
      <div class="section-header">
        <h2 class="section-title">最近教案</h2>
        <el-button text @click="handleViewLessons">
          查看全部 <el-icon><ArrowRight /></el-icon>
        </el-button>
      </div>
      
      <el-row :gutter="24">
        <el-col v-for="lesson in recentLessonPlans" :key="lesson._id" :xs="24" :sm="12" :lg="8">
          <div class="lesson-card" @click="viewLesson(lesson._id)">
            <div class="lesson-header">
              <h4 class="lesson-title">{{ lesson.title }}</h4>
              <el-dropdown @command="(cmd) => handleLessonAction(cmd, lesson)" @click.stop>
                <el-button :icon="More" circle text />
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="view">查看详情</el-dropdown-item>
                    <el-dropdown-item command="edit">编辑教案</el-dropdown-item>
                    <el-dropdown-item command="delete" divided>删除教案</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
            
            <div class="lesson-meta">
              <el-tag size="small">{{ lesson.subject }}</el-tag>
              <el-tag size="small" type="success">{{ lesson.grade }}</el-tag>
              <el-tag size="small" type="info">{{ lesson.courseType }}</el-tag>
            </div>
            
            <div class="lesson-stats">
              <div class="stat">
                <el-icon><View /></el-icon>
                <span>{{ lesson.views || 0 }}</span>
              </div>
              <div class="stat">
                <el-icon><Star /></el-icon>
                <span>{{ lesson.likes || 0 }}</span>
              </div>
              <div class="stat">
                <el-icon><Clock /></el-icon>
                <span>{{ formatDate(lesson.updatedAt) }}</span>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  DocumentAdd,
  Folder,
  User,
  Document,
  Reading,
  School,
  Search,
  Share,
  ArrowRight,
  More,
  View,
  Star,
  Clock,
  Top
} from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { lessonPlanApi, type LessonPlan } from '@/api/lessonPlan'
import { categoryApi } from '@/api/category'

const router = useRouter()
const authStore = useAuthStore()

// 统计数据
const stats = reactive({
  totalLessonPlans: 0,
  myLessonPlans: 0,
  totalSubjects: 0,
  totalGrades: 0
})

// 最近的教案
const recentLessonPlans = ref<LessonPlan[]>([])

// 快速操作处理函数
const handleCreateLesson = () => {
  if (!authStore.isAuthenticated) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  router.push('/lesson-plans/create')
}

const handleViewLessons = () => {
  if (!authStore.isAuthenticated) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  router.push('/lesson-plans')
}

const handleProfile = () => {
  if (!authStore.isAuthenticated) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  router.push('/profile')
}

// 查看教案
const viewLesson = (id: string) => {
  router.push(`/lesson-plans/${id}`)
}

// 编辑教案
const editLesson = (id: string) => {
  router.push(`/lesson-plans/${id}/edit`)
}

// 处理教案操作
const handleLessonAction = async (command: string, lesson: LessonPlan) => {
  switch (command) {
    case 'view':
      viewLesson(lesson._id)
      break
    case 'edit':
      editLesson(lesson._id)
      break
    case 'delete':
      try {
        await ElMessageBox.confirm(
          `确定要删除教案《${lesson.title}》吗？`,
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        await lessonPlanApi.delete(lesson._id)
        ElMessage.success('删除成功')
        loadStats()
      } catch (error: any) {
        if (error !== 'cancel') {
          ElMessage.error(error.message || '删除失败')
        }
      }
      break
  }
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (days === 0) {
    return '今天'
  } else if (days === 1) {
    return '昨天'
  } else if (days < 7) {
    return `${days}天前`
  } else {
    return date.toLocaleDateString('zh-CN', {
      month: '2-digit',
      day: '2-digit'
    })
  }
}

// 加载统计数据
const loadStats = async () => {
  console.log('=== 开始加载统计数据 ===')
  console.log('localStorage token:', localStorage.getItem('token'))
  console.log('authStore.token:', authStore.token)
  console.log('authStore.user:', authStore.user)
  console.log('authStore.isAuthenticated:', authStore.isAuthenticated)
  
  try {
    // 先加载分类统计
    console.log('正在加载分类统计...')
    const categoryResponse = await categoryApi.getCategoryStats()
    console.log('分类统计响应:', categoryResponse)
    if (categoryResponse.success && categoryResponse.data) {
      const categoryData = categoryResponse.data
      stats.totalLessonPlans = categoryData.summary.totalLessonPlans
      stats.totalSubjects = categoryData.summary.totalSubjects
      stats.totalGrades = categoryData.summary.totalGrades
    }
    
    // 直接尝试获取我的教案数据，不管认证状态
    console.log('正在尝试获取我的教案数据...')
    try {
      const myLessonsResponse = await lessonPlanApi.getMyList({ limit: 5 })
      console.log('我的教案响应:', myLessonsResponse)
      if (myLessonsResponse && myLessonsResponse.data) {
        stats.myLessonPlans = myLessonsResponse.data.pagination.total
        recentLessonPlans.value = myLessonsResponse.data.lessonPlans
        console.log('我的教案数量:', stats.myLessonPlans)
      }
    } catch (error: any) {
      console.error('加载我的教案失败:', error)
      // 如果获取失败（比如token无效），重置为0
      stats.myLessonPlans = 0
      recentLessonPlans.value = []
    }
  } catch (error: any) {
    console.error('加载统计数据失败:', error)
  }
  console.log('=== 统计数据加载完成 ===')
}

// 监听认证状态变化（监听token变化更可靠）
watch(() => authStore.token, () => {
  loadStats()
}, { immediate: false })

// 页面初始化
onMounted(() => {
  loadStats()
})
</script>

<style scoped>
.home {
  min-height: calc(100vh - 100px);
}

/* 欢迎区域 */
.welcome-section {
  padding: 60px 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.welcome-content {
  padding-right: 40px;
}

.welcome-title {
  font-size: 48px;
  font-weight: 700;
  line-height: 1.2;
  margin-bottom: 24px;
}

.title-gradient {
  background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.title-sub {
  font-size: 36px;
  color: #303133;
}

.welcome-description {
  font-size: 18px;
  color: #606266;
  line-height: 1.8;
  margin-bottom: 32px;
}

.welcome-actions {
  display: flex;
  gap: 16px;
  margin-bottom: 40px;
}

.welcome-stats {
  display: flex;
  gap: 40px;
}

.welcome-stats .stat-item {
  text-align: left;
}

.welcome-stats .stat-value {
  font-size: 32px;
  font-weight: 700;
  color: #409eff;
  margin-bottom: 4px;
}

.welcome-stats .stat-label {
  font-size: 14px;
  color: #909399;
}

/* 插画区域 */
.welcome-illustration {
  position: relative;
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.illustration-bg {
  position: relative;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #f5f7fa 0%, #e6e9f0 100%);
  border-radius: 24px;
  overflow: hidden;
}

.floating-card {
  position: absolute;
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
  animation: float 3s ease-in-out infinite;
}

.card-1 {
  top: 20%;
  left: 20%;
  animation-delay: 0s;
}

.card-2 {
  top: 50%;
  right: 25%;
  animation-delay: 1s;
}

.card-3 {
  bottom: 20%;
  left: 35%;
  animation-delay: 2s;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-20px);
  }
}

/* 功能特性 */
.features-section {
  background: #f5f7fa;
  padding: 80px 24px;
}

.section-header {
  text-align: center;
  margin-bottom: 48px;
}

.section-title {
  font-size: 32px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 12px;
}

.section-description {
  font-size: 16px;
  color: #606266;
}

.features-grid {
  max-width: 1200px;
  margin: 0 auto;
}

.feature-card {
  background: white;
  border-radius: 16px;
  padding: 32px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
  margin-bottom: 24px;
}

.feature-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #409eff 0%, #67c23a 100%);
  transform: scaleX(0);
  transition: transform 0.3s;
}

.feature-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 48px rgba(0, 0, 0, 0.12);
}

.feature-card:hover::before {
  transform: scaleX(1);
}

.feature-icon {
  width: 80px;
  height: 80px;
  margin: 0 auto 24px;
  background: #ecf5ff;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #409eff;
}

.feature-card h3 {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.feature-card p {
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
}

.feature-tag {
  position: absolute;
  top: 16px;
  right: 16px;
}

/* 统计数据 */
.stats-overview {
  padding: 80px 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.stat-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  position: relative;
  transition: all 0.3s;
  margin-bottom: 24px;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 48px rgba(0, 0, 0, 0.08);
}

.stat-icon {
  width: 56px;
  height: 56px;
  background: #f0f9ff;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #409eff;
  margin-bottom: 16px;
}

.stat-content {
  margin-bottom: 8px;
}

.stat-number {
  font-size: 32px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 4px;
}

.stat-number :deep(.el-statistic__number) {
  font-size: 32px;
  font-weight: 700;
}

.stat-trend {
  position: absolute;
  top: 24px;
  right: 24px;
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
}

.stat-trend.up {
  color: #67c23a;
}

.stat-trend.down {
  color: #f56c6c;
}

/* 最近教案 */
.recent-section {
  background: #f5f7fa;
  padding: 80px 24px;
}

.recent-section .section-header {
  max-width: 1200px;
  margin: 0 auto 48px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.recent-section .el-row {
  max-width: 1200px;
  margin: 0 auto;
}

.lesson-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 24px;
}

.lesson-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 48px rgba(0, 0, 0, 0.08);
}

.lesson-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.lesson-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.lesson-meta {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
}

.lesson-stats {
  display: flex;
  gap: 16px;
  color: #909399;
  font-size: 13px;
}

.lesson-stats .stat {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .welcome-section {
    padding: 40px 16px;
  }
  
  .welcome-content {
    padding-right: 0;
    text-align: center;
  }
  
  .welcome-title {
    font-size: 32px;
  }
  
  .title-sub {
    font-size: 24px;
  }
  
  .welcome-description {
    font-size: 16px;
  }
  
  .welcome-actions {
    justify-content: center;
  }
  
  .welcome-stats {
    justify-content: center;
  }
  
  .welcome-illustration {
    display: none;
  }
  
  .features-section,
  .stats-overview,
  .recent-section {
    padding: 40px 16px;
  }
  
  .section-title {
    font-size: 24px;
  }
  
  .recent-section .section-header {
    flex-direction: column;
    gap: 16px;
  }
}
</style>